package org.jage.student.missevo.solution.energy;

import java.util.Collection;

import org.jage.action.IActionContext;
import org.jage.action.IPerformActionStategy;
import org.jage.action.SingleAction;
import org.jage.address.IAgentAddress;
import org.jage.agent.AgentException;
import org.jage.agent.IAgent;
import org.jage.agent.ISimpleAggregate;
import org.jage.property.ClassPropertyContainer;
import org.jage.property.PropertyField;
import org.jage.platform.component.annotation.Inject;
import org.jage.student.missevo.solution.agent.MissEvoSimpleAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompareEnergyAction extends ClassPropertyContainer implements IPerformActionStategy {

	private final Logger log = LoggerFactory.getLogger(MissEvoSimpleAgent.class);
	
	@PropertyField(propertyName = "energyToPass")
	@Inject
	private double energyToPass;
	
	public void perfom(IAgent target, IActionContext context) throws AgentException {
		if (target == null) throw new IllegalArgumentException("target cannot be null");
		if (context == null) throw new IllegalArgumentException("context cannot be null");
		
		ISaveEnergyActionContext saveEnergyActionContext = (ISaveEnergyActionContext) context;
		MissEvoSimpleAgent targetAgent = (MissEvoSimpleAgent) target;
		
		int targentAgentKind = targetAgent.getKind();
		if (targentAgentKind == saveEnergyActionContext.getAgentKind()) {
			saveEnergyActionContext.setTransferredEnergy(0.0);
			log.info("{} is of same kind. Energy won't be taken.", new Object[] { targetAgent.toString() });
			return;
		}
		
	    double targetAgentEnergy = targetAgent.getEnergy();
	    double currentAgentEnergy = saveEnergyActionContext.getEnergy();
	
		double passed = 0.0;
		
	    if (targetAgentEnergy > currentAgentEnergy) {
	    	passed = Math.min(currentAgentEnergy, energyToPass);
	    	targetAgent.setEnergy(targetAgentEnergy + passed);
	        saveEnergyActionContext.setTransferredEnergy(-passed);
	    }
	    else {
	    	passed = Math.min(targetAgentEnergy, energyToPass);    	
	    	targetAgent.setEnergy(targetAgentEnergy - passed);
	        saveEnergyActionContext.setTransferredEnergy(passed);
	    }
	    
	    log.info("{} takes {} energy from someone", new Object[] { targetAgent.toString(), passed });
	}
	
	public void finish(IAgent target, IActionContext context) {
	    // TODO Auto-generated method stub
	    
	}
	
	public Collection<IAgentAddress> init(ISimpleAggregate aggregate,
	    SingleAction action) throws AgentException {
	    // TODO Auto-generated method stub
	    return null;
	}

}
